package com.wjy.game.viewer;

import com.wjy.game.ConnectServer;
import com.wjy.game.service.ServerSocketService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.*;
import java.awt.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author wjy
 * @date 2025/5/22 10:42
 * @description 服务端管理界面
 */
@Data
@Slf4j
@Component
public class ManagerViewer extends Viewer{

    private JLabel connectLabel = new JLabel("当前连接数:");
    private JLabel connectNumLabel = new JLabel("0");

    private JTextArea messageBoard = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane(messageBoard); // 使用 JScrollPane 包装 JTextArea
    private final JButton clearButton = new JButton("清除显示");
    private final JButton statusButton = new JButton("服务器状态");
    private final JButton closeButton = new JButton("关闭服务器");

    @Resource
    private ConnectServer server;

    @Override
    protected void repaintUI() {

        Panel connectPanel = new Panel();
        connectPanel.setBounds(0, 0, 800, 40);
        connectPanel.setLayout(new FlowLayout());
        connectPanel.add(connectLabel);
        connectPanel.add(connectNumLabel);
        add(connectPanel, BorderLayout.NORTH);

        Panel messagePanel = new Panel();
        // 设置 JScrollPane 的大小
        scrollPane.setPreferredSize(new Dimension(700, 400));
        messagePanel.setBounds(50, 40, 800, 400);
        messagePanel.add(scrollPane);
        add(messagePanel, BorderLayout.CENTER);

        Panel buttonPanel = new Panel();
        buttonPanel.setBounds(0, 430, 300, 50);
        buttonPanel.setLayout(new FlowLayout());
        clearButton.setSize(20, 25);
        buttonPanel.add(clearButton);
        statusButton.setSize(75, 25);
        buttonPanel.add(statusButton);
        closeButton.setSize(75, 25);
        buttonPanel.add(closeButton);
        add(buttonPanel, BorderLayout.SOUTH);

    }

    @Override
    protected void actions() {
        int port = 5024;
        statusButton.addActionListener(e -> {
            try {
                messageBoard.append(String.format("服务器信息:%s:%d\n", InetAddress.getLocalHost().getHostAddress(), port));
            } catch (UnknownHostException ex) {
                log.error("未知主机");
            }
        });
        clearButton.addActionListener(e -> {
            messageBoard.setText("");
        });
        closeButton.addActionListener(e -> {
            server.stop();
            System.exit(0);
        });
        server.start(port);

    }

    @Override
    protected LayoutManager getLayoutManager() {
        return new BorderLayout();
    }

    @Override
    public int getWidth() {
        return 800;
    }

    @Override
    public int getHeight() {
        return 500;
    }
}
